/*
 * FileDictionary.cpp
 *
 *  Created on: Sep 13, 2011
 *      Author: srihari
 */

#include "FileDictionary.h"
using namespace std;

static int curBarrel = 0;

FileDictionary::FileDictionary() {
	nextDocId = 0;
	config* configInstance = config::getInstance();
	dirPath = configInstance->getValue("path_to_dict_store_dir");
}

FileDictionary::~FileDictionary() {
}

bool FileDictionary::writeFilePaths()
{
	string filepath = dirPath + "/filePathsStore" + CUtilities::number_to_string(curBarrel) + ".txt";
	filePathStore.open(filepath.c_str());
	string fileIndexPath = dirPath + "/fileDictionaryIndexStore.txt";
	fileDictionaryIndexStore.open(fileIndexPath.c_str(), ios::app);
	string filePath;
	string fileLoc;

	size_t fileId = 0;
	int offset = 0;
	for (int i = 0; i < listOfFilePaths.size(); i++) {
		filePath = listOfFilePaths[i];

		// Write File Path
		filePathStore << filePath ;
		fileId = (curBarrel * BARREL_SIZE) + i;
		fileLoc =  CUtilities::number_to_string(curBarrel).append(":").append(CUtilities::number_to_string(offset));
		//FileDictionary::fileDictionaryIndex.insert(fileId, fileLoc);
		// cout << fileId << " " <<  fileLoc << "\n";
		// cout << "File path: " << filePath << " Size:" << filePath.size() << endl;
		fileDictionaryIndexStore << fileId << " " << fileLoc << "\n";

		// Offset for next file
		offset += filePath.size();
	}

	// Close the file
	curBarrel++;
	listOfFilePaths.clear();
	filePathStore.close();
	fileDictionaryIndexStore.close();
}

std::map<string,size_t> FileDictionary::getFileNameIdMap() const
{
    return fileNameIdMap;
}

void FileDictionary::setFileNameIdMap(std::map<string,size_t> fileNameIdMap)
{
    this->fileNameIdMap = fileNameIdMap;
}

size_t FileDictionary::addFilePath(CDocument doc)
{
	string filePath = doc.get_resource_name();
	string fileName;
	listOfFilePaths.push_back(filePath + "$");
	if (listOfFilePaths.size() == BARREL_SIZE) {
		writeFilePaths();
	}
	fileName = CUtilities::extractFileNameFromPath(filePath);
	CUtilities::to_lower(fileName);

	// For Wiki only
	// if (doc.get_doc_class_type() == 2) {
		cout << "FILENAME: " << fileName << endl;
		fileNameIdMap.insert(pair<string, size_t>(fileName, nextDocId));
	// }
	return nextDocId++;
}







